package com.geping.etl.common.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.geping.etl.common.entity.Sys_DepartmentVo;
import com.geping.etl.common.service.Sys_UserService;
import com.geping.etl.common.util.BusinessResponse;
import com.geping.etl.common.util.BusinessResult;
import com.geping.etl.common.util.Constants;
import com.geping.etl.utils.EnvUitl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.geping.etl.common.entity.Sys_Department;
import com.geping.etl.common.service.Sys_DepartmentService;

@RestController
@Slf4j
public class Sys_DepartmentController {


    @Autowired
    private Sys_DepartmentService sys_DepartmentService;

    @Autowired
    private Sys_UserService sysUserService;


    //查询所有用户信息
    @RequestMapping(value = "/sys_department", method = RequestMethod.GET)
    public ModelAndView getAllSys_Department() {
        ModelAndView model = new ModelAndView();
        List<Sys_Department> list = sys_DepartmentService.findAllSys_Department();
        List<Sys_DepartmentVo> listVo = new ArrayList<>();
        list.forEach(dept -> {
            listVo.add(sys_DepartmentService.getSysDeptVoBySysDept(dept));
        });
        model.addObject("list", listVo);
        model.addObject("taiwanUser", EnvUitl.props.getProperty("taiwan.user"));
        if (Constants.TAIWAN_BANK_USER_ON.equals(EnvUitl.props.getProperty("taiwan.user"))) {
            model.addObject("title", "分行信息");
        } else {
            model.addObject("title", "部门信息");
        }
        model.setViewName("common/sys_department");
        return model;
    }


    //模糊查询部门信息
    @RequestMapping(value = "/getSys_DepartmentByLikeDepartmentName", method = RequestMethod.GET)
    public ModelAndView getSys_DepartmentByLikeDepartmentName(HttpServletRequest request) {
        ModelAndView model = new ModelAndView();
        try {
            String departmentName = request.getParameter("departmentName").replace("%", ",%");
            departmentName = departmentName.replace("_", ",_");

            List<Sys_Department> list = new ArrayList<>();
            List<Sys_DepartmentVo> listVo = new ArrayList<>();
            if (StringUtils.isNotBlank(departmentName)) {
                if (Constants.TAIWAN_BANK_USER_ON.equals(EnvUitl.props.getProperty("taiwan.user"))) {
                    list = sys_DepartmentService.getSys_DepartmentByLikeDescription(departmentName);
                } else {
                    list = sys_DepartmentService.getSys_DepartmentByLikeDepartmentName(departmentName);
                }
            } else {
                list = sys_DepartmentService.findAllSys_Department();
            }
            list.forEach(dept -> {
                listVo.add(sys_DepartmentService.getSysDeptVoBySysDept(dept));
            });
            model.addObject("list", listVo);
            model.addObject("departmentName", departmentName.replace(",_", "_").replace(",%", "%"));
            model.setViewName("common/sys_department");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return model;
    }


    //新增部门信息
    @RequestMapping(value = "/addSys_Department", method = RequestMethod.POST)
    public void addSys_Department(HttpServletRequest request, HttpServletResponse response) {
        String departmentName_add = request.getParameter("departmentName_add");
        String description_add = request.getParameter("description_add");
        String departmentId_add = request.getParameter("departmentId_add");
        PrintWriter out;
        try {
            out = response.getWriter();
            if (departmentName_add.length() > 255 || description_add.length() > 255) {
                out.write("3");
                out.flush();
                out.close();
            } else {
                List<Sys_Department> IsRepeatList = sys_DepartmentService.getSys_DepartmentByDepartmentName(departmentName_add);
                //添加分行号和分行名称的查重
                if (Constants.TAIWAN_BANK_USER_ON.equals(EnvUitl.props.getProperty("taiwan.user"))) {
                    IsRepeatList = sys_DepartmentService.getSys_DepartmentByLikeDepartmentIdAndDepartmentName(departmentId_add, departmentName_add);
                    if (IsRepeatList.size() > 0) {
                        out.write("4");
                        out.flush();
                        out.close();
                        return;
                    } else {
                        IsRepeatList = sys_DepartmentService.getSys_DepartmentByDescriptionAndDepartmentName(description_add, departmentName_add);
                        if (IsRepeatList.size() > 0) {
                            out.write("5");
                            out.flush();
                            out.close();
                            return;
                        }
                    }
                }
                if (IsRepeatList.size() > 0) {
                    out.write("2");
                    out.flush();
                    out.close();
                } else {
                    Sys_Department sys = new Sys_Department();
                    sys.setDepartmentName(departmentName_add);
                    sys.setDescription(description_add);
                    sys.setDepartmentId(departmentId_add);
                    Sys_Department sys_department = sys_DepartmentService.saveDept(sys);
                    try {
                        out = response.getWriter();
                        if (sys_department != null) {
                            out.write("1");
                        } else {
                            out.write("0");
                        }
                        out.flush();
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }


    //修改部门
    @RequestMapping(value = "/editSys_Department", method = RequestMethod.POST)
    public void editSys_Department(HttpServletRequest request, HttpServletResponse response) {
        String id_edit = request.getParameter("editId");
        String departmentName_edit = request.getParameter("departmentName_edit");
        String departmentId_edit = request.getParameter("departmentId_edit");
        String description_edit = request.getParameter("description_edit");


        PrintWriter out;
        try {
            out = response.getWriter();
            if (departmentName_edit.length() > 255 || description_edit.length() > 255) {
                out.write("3");
                out.flush();
                out.close();
            } else {
                List<Sys_Department> sysIsRepeatList = sys_DepartmentService.getSys_DepartmentByLikeDepartmentName(departmentName_edit);
                Sys_Department oldDept = sys_DepartmentService.getSys_DepartmentById(Integer.valueOf(id_edit));

                //添加分行号和分行名称的查重
                if (Constants.TAIWAN_BANK_USER_ON.equals(EnvUitl.props.getProperty("taiwan.user"))) {
                    sysIsRepeatList = sys_DepartmentService.getSys_DepartmentByLikeDepartmentIdAndDepartmentName(departmentId_edit, departmentName_edit);
                    if (sysIsRepeatList.size() > 0 && !String.valueOf(sysIsRepeatList.get(0).getId()).equals(id_edit)) {
                        out.write("4");
                        out.flush();
                        out.close();
                        return;
                    } else {
                        sysIsRepeatList = sys_DepartmentService.getSys_DepartmentByDescriptionAndDepartmentName(description_edit, departmentName_edit);
                        if (sysIsRepeatList.size() > 0 && !String.valueOf(sysIsRepeatList.get(0).getId()).equals(id_edit)) {
                            out.write("5");
                            out.flush();
                            out.close();
                            return;
                        }
                    }
                    departmentId_edit = departmentId_edit + id_edit;
                } else {
                    departmentId_edit = id_edit;
                }
                if (sysIsRepeatList.size() > 0 && !String.valueOf(sysIsRepeatList.get(0).getId()).equals(id_edit)) {
                    out.write("2");    //2表示部门名称重复
                    out.flush();
                    out.close();
                } else {
                    int result = sys_DepartmentService.updateSys_Department(Integer.valueOf(id_edit), departmentName_edit, description_edit, departmentId_edit);
                    if(oldDept != null) {
                        sysUserService.updateDeptIdByOldDeptId(oldDept.getDepartmentId(), departmentId_edit);
                    }
                    if (result > 0) {
                        out.write("1");
                    } else {
                        out.write("0");
                    }
                }

                out.flush();
                out.close();
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }


    //逻辑删除用户
    @RequestMapping(value = "/deleteSys_Department", method = RequestMethod.POST)
    public void deleteSys_Department(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        int result = 0;
        Sys_Department oldDept = sys_DepartmentService.getSys_DepartmentById(Integer.valueOf(id));
        result = sys_DepartmentService.deleteSys_Department(Integer.valueOf(id));
        if(oldDept != null) {
            sysUserService.deleteUserByDeptId(oldDept.getDepartmentId());
        }
        JSONObject permision = new JSONObject();
        PrintWriter out;
        try {
            out = response.getWriter();
            permision.put("result", result);
            out.print(permision.toString());
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //Excel导出部门信息
    @RequestMapping(value = "/exportSys_Department", method = RequestMethod.GET)
    public void exportSys_Department(HttpServletRequest request, HttpServletResponse response) {
        String excelType = request.getParameter("excelType");
        String departmentName = "";
        String fileName = "";
        Workbook wb = null;
        Sheet sheet = null;
        OutputStream out = null;
        List<Sys_Department> list = null;
        List<Sys_DepartmentVo> listVo = new ArrayList<>();
        try {
            response.setContentType("text/html");
            response.setContentType("text/plain; charset=utf-8");
            response.setContentType("octets/stream");
			/*request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/x-download");
			response.setContentType("octets/stream");*/

            if (request.getParameter("departmentName") != null && !("").equals(request.getParameter("departmentName"))) {
                departmentName = URLDecoder.decode(request.getParameter("departmentName"), "utf-8");
                if (Constants.TAIWAN_BANK_USER_ON.equals(EnvUitl.props.getProperty("taiwan.user"))) {
                    list = sys_DepartmentService.getSys_DepartmentByLikeDescription(departmentName);
                } else {
                    list = sys_DepartmentService.getSys_DepartmentByLikeDepartmentName(departmentName);
                }
            } else {
                list = sys_DepartmentService.findAllSys_Department();

            }
            list.forEach(dept -> {
                listVo.add(sys_DepartmentService.getSysDeptVoBySysDept(dept));
            });
            //headers:excel中表列标题名
            String[] headers = null;
            if (Constants.TAIWAN_BANK_USER_ON.equals(EnvUitl.props.getProperty("taiwan.user"))) {
                headers = new String[]{"ID", "分行号", "分行名称", "部门名称", "是否删除"};
                fileName = "分行信息记录";
            } else {
                headers = new String[]{"ID", "部门代码", "部门名称", "部门描述", "是否删除"};
                fileName = "部门信息记录";
            }
            if (excelType.equals("xls")) {
                fileName = fileName + ".xls";   //设置下载的文件名称
                wb = new HSSFWorkbook(); // 创建一个新的excel
            } else if (excelType.equals("xlsx")) {
                fileName = fileName + ".xlsx";   //设置下载的文件名称
                wb = new XSSFWorkbook(); // 创建一个新的excel
            } else {

            }

            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));

            sheet = wb.createSheet("sheet1"); // 创建sheet页
            Font font = wb.createFont();
            font.setFontName("仿宋_GB2312");
            font.setFontHeightInPoints((short) 14);
            font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
            CellStyle style = wb.createCellStyle();
            style.setAlignment(XSSFCellStyle.ALIGN_CENTER);// 水平对齐
            style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); // 垂直对齐
            style.setBorderTop(BorderStyle.THIN);// 设置边框
            style.setBorderBottom(BorderStyle.THIN);
            style.setBorderLeft(BorderStyle.THIN);
            style.setBorderRight(BorderStyle.THIN);
            style.setFont(font);

            Font font1 = wb.createFont();
            font1.setFontName("宋体");
            font1.setFontHeightInPoints((short) 10);
            font1.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
            CellStyle style1 = wb.createCellStyle();
            style1.setAlignment(XSSFCellStyle.ALIGN_CENTER);// 水平对齐
            style1.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); // 垂直对齐
            style1.setBorderTop(BorderStyle.THIN);// 设置边框
            style1.setBorderBottom(BorderStyle.THIN);
            style1.setBorderLeft(BorderStyle.THIN);
            style1.setBorderRight(BorderStyle.THIN);
            style1.setFont(font1);

            Row row = sheet.createRow(0); // 创建第一行
            // 创建第一行第i格,循环创建表头标题行
            for (int i = 0; i < headers.length; i++) {
                Cell cell = row.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(style);
                //设置自动宽
//				sheet.autoSizeColumn(i,true);
                sheet.setColumnWidth(i, 30 * 256);
            }

            for (int i = 0; i < listVo.size(); i++) {
                Row rowPlus = sheet.createRow(i + 1); // 从第二行开始创建
                Sys_Department department = list.get(i); // 获取集合中的数据

                Cell cell0 = rowPlus.createCell(0); // 创建第i+1行第i格
                cell0.setCellValue(department.getId());
                cell0.setCellStyle(style1);

                Cell cell1 = rowPlus.createCell(1);
                cell1.setCellValue(department.getDepartmentId());
                cell1.setCellStyle(style1);

                if (Constants.TAIWAN_BANK_USER_ON.equals(EnvUitl.props.getProperty("taiwan.user"))) {
                    Cell cell2 = rowPlus.createCell(2);
                    cell2.setCellValue(department.getDescription());
                    cell2.setCellStyle(style1);

                    Cell cell3 = rowPlus.createCell(3);
                    cell3.setCellValue(department.getDepartmentName());
                    cell3.setCellStyle(style1);
                } else {
                    Cell cell2 = rowPlus.createCell(2);
                    cell2.setCellValue(department.getDepartmentName());
                    cell2.setCellStyle(style1);

                    Cell cell3 = rowPlus.createCell(3);
                    cell3.setCellValue(department.getDescription());
                    cell3.setCellStyle(style1);
                }

                Cell cell4 = rowPlus.createCell(4);
                cell4.setCellValue(department.getIsDelete());
                cell4.setCellStyle(style1);
            }
            out = response.getOutputStream();
            wb.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }

                if (wb != null) {
                    wb.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }


}
